﻿using System;
using System.Collections.Generic;
using System.Text;

using PostSharp.Laos;
using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace EntlibAOP.Security.Cryptography
{
    [Serializable]
    [AttributeUsage(AttributeTargets.Method)]
    public class EncryptionAttribute : OnMethodBoundaryAspect
    {        

        /// <summary>
        /// This property represent the name of the configuration setting which contain the cryptography 
        /// configuration information
        /// </summary>
        public string ConfigSettingName
        {
            get;
            set;
        }

        /// <summary>
        /// This method help to intercept the return value and ecrypt it before returned to the calling code
        /// </summary>
        /// <param name="eventArgs">Argument passed to the event handler</param>
        public override void OnSuccess(MethodExecutionEventArgs eventArgs)
        {
            if (string.IsNullOrEmpty(ConfigSettingName))
            {
                throw new Exception("InValid Configuration");
            }
            
            
            eventArgs.ReturnValue = Cryptographer.EncryptSymmetric(ConfigSettingName, eventArgs.ReturnValue.ToString());
            
        }

        private byte[] getByteArrayWithObject(Object o)
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf1 = new BinaryFormatter();
            bf1.Serialize(ms, o);
            return ms.ToArray();
        }

        private object getObjectWithByteArray(byte[] theByteArray)
        {
            MemoryStream ms = new MemoryStream(theByteArray);
            BinaryFormatter bf1 = new BinaryFormatter();
            ms.Position = 0;

            return bf1.Deserialize(ms);
        }

    }
}
